#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update:


'''
'''

__revision__ = '0.1'
__author__ = 'lxd'
import time
import config

class Helper():
    def __init__(self,log,dm, main_helper, timeWorks):
        self.log = log
        self.dm = dm
        self.main = main_helper

        self.timeWorks = timeWorks
        self.build_times = []#所有正在建造中的建筑时间列表

##########get build status##########
    def _getBuildNum(self):
        """发现建筑排程卡就返回5个，否则2个
        """
        if self.dm.findMultiColor('955637,-3|16|d775ca,15|8|b98b69'):
            num = 5
        else:
            num = 2
        self.log.debug('canBuildNum:%s' %num)
        return num

    def _getLeftTimes(self):
        """通过城池动态框获取目前正在建造的建筑剩余时间
        """
        if not self.dm.findStr(u'当前没有建造中的建筑'):
            #TODO:城防也会有建造中
            builds_pos = self.dm.findStrs(u'建造中')
            if builds_pos:
                for pos in builds_pos:
                    x0, y0, x1, y1 = pos[0]+75, pos[1]-1, pos[0]+134, pos[1]+14
                    atime = self.dm.ocr(x0, y0, x1, y1)
                    if atime:
                        self.build_times.append(atime)
        self.log.debug('leftTimes:%s' %self.build_times)


    def getCanBuildNum(self):
        """得到可以建造的数量, 
        """
        canBuildNum = self._getBuildNum()
        self.main.showTip()
        self._getLeftTimes()
        canNum = canBuildNum - len(self.build_times)
        self.log.debug('still can build num %s' %canNum)
        return canNum

    def __recordBuildTime(self, atime):
        """建造时间记录
        """
        data = {'kind':'build'}
        self.timeWorks.setTime(data, atime)
        self.log.debug('record build time:%s' %atime)

    def recordBuildTimes(self):
        """将城池动态框里的时间记录下来
        """
        self.timeWorks.clear('build')
        for leftTime in self.build_times:
            s = leftTime.split(':')
            assert(len(s) == 3)
            atime = int(s[0])*60*60+int(s[1])*60+int(s[2])
            self.__recordBuildTime(atime)

##########work##########
    def _getBuildPos(self, build):
        """得到build记录的相对坐标
        """
        return map(int, build[3][1:-1].split(','))

    def findBuild(self, build):
        """找到该建筑物，
        """
        def findCity():
            if build[2] == u'主城':
                self.main.gotoMainCity()
            elif build[2] == u'第一分城': 
                self.main.gotoFirstCity()
            elif build[2] == u'第二分城': 
                self.main.gotoSecondCity()
            elif build[2] == u'第三分城': 
                self.main.gotoThirdCity()
            elif build[2] == u'第四分城': 
                self.main.gotoFourthCity()


        def drag(pos):
            #拖鼠标使得建筑物位置合适
            drag_pos = self.main.getDragPos(pos)
            self.dm.moveTo(drag_pos)
            pos = self._getBuildPos(build)
            self.dm.drag(-pos[0], -pos[1], True)

        def checkRank(center_pos):
            #找不到级别算作ok
            def getRank(center_pos):
                """由感应坐标得到级别
                """
                pos = self._getBuildPos(build)
                build_name_pos = pos[0]+center_pos[0]+23, pos[1]+center_pos[1]-35
                self.log.debug('build name pos is %s' %str(build_name_pos))
                return self.main.getRank(build_name_pos)

            rank = int(build[1])
            show_rank = getRank(center_pos)
            if show_rank:
                self.log.debug('real rank is %s' %show_rank)
                if rank < show_rank:
                    build[4] = config.updateStatus['done']
            return True
            
        findCity()
        pos = self.main.getCenterBuildAndPos()[1]
        drag(pos)
        pos = self.main.getCenterBuildAndPos()[1]
        self.dm.setCenterPos(pos)
        self.log.debug('orgin_x, orign_y is:%s' %str(pos))
        return checkRank(pos)

    def clickBuild(self, build):
        """点击建筑物然后升级, point为建筑物名字相对坐标
        """
        def canUpdate(pos):
            """点击建筑物之后得到建筑物状态, pos是建筑物点击感应坐标
            """
            x0, x1, y0, y1 = pos[0]+28, pos[1]-7, pos[0]+60, pos[1]+9
            str = self.dm.ocr(x0, x1, y0, y1, 'ffcc66')
            if str == u'升级':
                return True
            else:
                return False

        point = self._getBuildPos(build)
        self.dm.click(point)#点击建筑物
        if canUpdate(point):
            self.dm.click(point[0]+43, point[1]+3)#点升级
            time.sleep(1)
            if self.main.closeTipMsg():#条件不足
                build[4] = config.updateStatus['notallow']
            else:
                build[4] = config.updateStatus['process']
        else:
            self.dm.click(point[0]-41, point[1]+1)#取消
            build[4] = config.updateStatus['process']


